<?php

namespace app\home\services;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelVirtual;
use app\home\loader\Model;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;
use yiqiniu\extend\facade\Db;

/**
 * 前端扫码,临时记录表
 */
class VirtualScanTempLogService extends BaseService
{

    /**
     * 导购扫码商品记录
     */
    public function SaveScanLog(array $params)
    {
        $model = ModelVirtual::VirtualScanTempLog();
        $product = ModelMerchant::Product()->where('mer_id', $params['mer_id'])->where('code', $params['product_code'])->find();
        if (empty($product)) {
            api_exception(400, '商品不存在,请联系经销商.');
        }
        if (empty($params['vp_id']) && !empty($params['order_no'])) {
            $params['vp_id'] = $model->where(['mer_id' => $params['mer_id'], 'order_no' => $params['order_no']])
                ->value(null, 'vp_id');
        }
        // 1.获取活动的商品
        // 2.判断提交的商品是否全部在活动中
        $promo_product = ModelVirtual::VirtualPromoProduct()->where('mer_id', $params['mer_id'])->where('vp_id', $params['vp_id'])->column('num', 'product_code');
        if (empty($promo_product) || empty($promo_product[$params['product_code']])) {
            throw  new Exception('该商品未参加活动，如有疑惑，请联系供货商！', API_ERROR);
        }
        $promModel = Model::VirtualPromo();
        $virtual_data = [];
        if (empty($params['order_no'])) {
            $model->where('vp_id', $params['vp_id'])->where('mer_id', $params['mer_id'])->where('user_id', $params['user_id'])->delete();
            $order_no = make_unique_no();

        } else {
            $order_no = $params['order_no'];
            $virtual_data = Cache::get($order_no);
        }
        $status = 0;
        $insert = false;
        if (empty($virtual_data)) {
            $params['order_no'] = $order_no;
            $now = Dt()->format(2);
            $model->valiProduct($params['order_no'],$params['product_code']);
            $virtual_data = $promModel->where('id', $params['vp_id'])->where('begin_time', '<=', $now)->where('end_time', '>=', $now)
                ->field('id,title,option,salesman,limit_num,union_rule,product_type,scanned_num')
                ->where('status', 1)->find();
            if (empty($virtual_data)) {
                throw  new Exception('活动无效', API_ERROR);
            }
            // 联合活动时, 联合规格不能为空
            if ($virtual_data['product_type'] === 2 && empty($virtual_data['union_rule'])) {
                throw  new Exception('活动设置异常,请联系经销商.', API_ERROR);
            }
            // 判断总限制数
            if ($virtual_data['limit_num'] > 0 && $virtual_data['scanned_num'] > $virtual_data['limit_num']) {
                throw  new Exception('活动领取次数已用完,请联系销售商.', API_ERROR);
            }
            // 活动日限制数量
            if (!empty($virtual_data['salesman']['day_num']) && $virtual_data['salesman']['day_num'] > 0) {
                $used_num = $promModel->userScanNumForToday($params['mer_id'], $params['vp_id'], $params['user_id']);
                if ($used_num > $virtual_data['salesman']['day_num']) {
                    throw  new Exception('您今天扫码次数已达到上限,请每天继续扫码参加活动.', API_ERROR);
                }
            }
            $insert_log = [];
            if ($virtual_data['product_type'] === 1) {
                $status = 1;
                $insert_log[] = [
                    'order_no' => $order_no,        // 订单号
                    'mer_id' => $params['mer_id'],        // 商户编号
                    'vp_id' => $params['vp_id'],        // 活动ID
                    'user_id' => $params['user_id'],        // 导购ID
                    'product_code' => $params['product_code'],        // 商品码
                    'num' => 0,        // 已扫数
                    'vp_num' => 1,        // 需扫数
                ];
            } else {
                foreach ($promo_product as $product_code => $num) {
                    $insert_log[] = [
                        'order_no' => $order_no,        // 订单号
                        'mer_id' => $params['mer_id'],        // 商户编号
                        'vp_id' => $params['vp_id'],        // 活动ID
                        'user_id' => $params['user_id'],        // 导购ID
                        'product_code' => $product_code,        // 商品码
                        'num' => 0,        // 已扫数
                        'vp_num' => $num,        // 需扫数
                    ];
                }
            }

            $insert = true;
            Cache::set($order_no, $virtual_data, DAY_SECOND);
        } else {
            $union_option = $virtual_data['union_rule'];
            $product_type = $virtual_data['product_type'];
            if ($product_type === 2) {
                $rule = $union_option['rule'];
                $scan_log = $model->where('order_no', $order_no)->where('vp_id', $params['vp_id'])->where('mer_id', $params['mer_id'])->where('user_id', $params['user_id'])->column(null, 'num', 'product_code');
                if ($rule == 2) {
                    $rule_num = $union_option['sum'];
                    $num = array_sum(array_values($scan_log));
                    if ($num < $rule_num) {
                        $insert = true;
                    }
                    if ($rule_num - $num <= 1) {
                        $status = 1;
                    }
                } else {
                    $rule_num = $promo_product[$params['product_code']];
                    $num = $scan_log[$params['product_code']] ?? 0;
                    if ($num < $rule_num) {
                        $insert = true;
                    }
                    if ($rule_num - $num <= 1) {
                        unset($promo_product[$params['product_code']]);
                        $com = true;
                        foreach ($promo_product as $code => $num) {
                            $scan_num = $scan_log[$code] ?? 0;
                            if ($scan_num < $num) {
                                $com = false;
                            }
                        }
                        if ($com) {
                            $status = 1;
                        }
                    }
                }
            } elseif ($product_type === 1) {
                $status = 1;
            }
        }
        if (!empty($insert_log)) {
            $model->insertAll($insert_log);
        }
        if ($insert) {
            $model->removeOption()
                ->where('order_no', $order_no)
                ->where('vp_id', $params['vp_id'])
                ->where('mer_id', $params['mer_id'])
                ->where('user_id', $params['user_id'])
                ->where('product_code', $params['product_code'])
                ->update(null, ['num' => Db::raw('num+1')]);
        }
        return ['order_no' => $order_no, 'status' => $status];
    }


    /**
     * 获取用户扫码信息列表
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function list(array $datas = []): array
    {
        $data = ModelVirtual::VirtualScanTempLog()->list($datas, ['user_id', 'order_no', 'product_code', 'num', 'vp_num', 'vp_id']);
        if (empty($data)) {
            throw  new Exception('订单不存在，请先扫码', API_SUCCESS);
        }
        $virtual_data = Model::VirtualPromo()->getValidPromInfo($data[0]['vp_id'], $data[0]['user_id']);
        $product_title = ModelMerchant::Product()->where('mer_id', $datas['mer_id'])
            ->where('code', 'in', array_column($data, 'product_code'))
            ->column(null, 'title', 'code');
        $sum_product_num = 0;
        foreach ($data as $key => $v) {
            $data[$key]['product_title'] = '';
            if (isset($product_title[$v['product_code']])) {
                $data[$key]['product_title'] = $product_title[$v['product_code']];
            }
            unset($data[$key]['user_id'], $data[$key]['vp_id']);
            $sum_product_num += $v['num'];
        }

        return [
            'small_ticket' => $virtual_data['small_ticket'],
            'recheck_record' => $virtual_data['recheck_record'],
            'title' => $virtual_data['title'],
            'rule' => $virtual_data['union']['rule'],
            'vp_product_num' => $virtual_data['union']['sum'],
            'product_num' => $sum_product_num,
            'product_list' => $data
        ];
    }
}
